import _ from 'lodash';
import HttpClient from '../commons/http-client';
import {FormStatus, updateAppState} from '../reducers/app-state';
import {fetchUserInfo} from './auth-actions';
import {updateUser, UserType} from '../reducers/user';
import {updateAssociateAccount} from '../reducers/associate-account';
import Toast from '../components/toast';
import {I18n} from '../reducers/intl';

export function submit(form, type) {
  return async dispatch => {
    for (const key in form) {
      if (!form[key]) {
        delete form[key];
      }
    }
    let params = null;
    if ([UserType.clinic, UserType.dentist].includes(type)) {
      params = {
        ...form,
        clinic_name: form.clinic_name,
        owner_email: form.bindAccount,
      };
    } else {
      params = {
        info: {
          ...form,
          vendor_name: form.vendor_name,
        },
        owner_email: form.bindAccount,
        products: {
          fixed_products: Object.values(form.fixed || {}).filter(
            product => product.enabled,
          ),
          remv_arch_products: Object.values(form.remvArch || {}).filter(
            product => product.enabled,
          ),
        },
      };
    }
    try {
      dispatch(updateAppState({formStatus: FormStatus.PENDING}));
      const profileRep = await HttpClient.put(
        `/web/${
          [UserType.clinic, UserType.dentist].includes(type)
            ? UserType.dentist
            : 'vend/vendor'
        }/my_info`,
        params,
      );
      await dispatch(fetchUserInfo());
      dispatch(updateAppState({formStatus: FormStatus.SUCCESS}));
    } catch (e) {
      dispatch(updateAppState({formStatus: FormStatus.FAIL}));
      throw e;
    }
  };
}

export function updateSupplier(form, fixed, remvArch) {
  return async dispatch => {
    // eslint-disable-next-line no-restricted-syntax
    for (const key in form) {
      if (!form[key]) {
        delete form[key];
      }
    }
    const params = {
      info: {
        ...form,
        vendor_name: form.name,
      },
      products: {
        fixed_products: Object.values(fixed).filter(product => product.enabled),
        remv_arch_products: Object.values(remvArch).filter(
          product => product.enabled,
        ),
      },
    };
    try {
      dispatch(updateAppState({formStatus: FormStatus.PENDING}));
      const profileRep = await HttpClient.put(
        '/web/vend/vendor/my_info',
        params,
      );
      await dispatch(fetchUserInfo());
      dispatch(updateAppState({formStatus: FormStatus.SUCCESS}));
    } catch (e) {
      dispatch(updateAppState({formStatus: FormStatus.FAIL}));
      throw e;
    }
  };
}

export function update(user) {
  return async dispatch => {
    dispatch(updateUser(user));
  };
}

export function searchAccount(value, type) {
  return async dispatch => {
    try {
      const rep = await HttpClient.get(
        `/web${
          [UserType.technician, UserType.provider].includes(type)
            ? '/vend/vendor'
            : '/dentist'
        }/query_owner?email=${value}`,
      );
      const data = _.get(rep, 'data.data', {});
      if (data.email === value) {
        dispatch(addAssociate(value, type));
      }
      dispatch(
        updateAssociateAccount({
          id: data.id,
          name: data.vendor_name,
          email: data.email,
        }),
      );
    } catch (e) {
      if (e.message === 'Request failed with status code 404') {
        Toast.show(I18n.t('toast.associateFailed'));
      } else {
        Toast.show(e.message);
      }
    }
  };
}

export function addAssociate(email, type) {
  return async dispatch => {
    await HttpClient.put(
      `/web${
        [UserType.technician, UserType.provider].includes(type)
          ? '/vend/vendor'
          : '/dentist'
      }/add_owner`,
      {email},
    );
    dispatch(fetchUserInfo());
  };
}

export function removeAssociate(id, type) {
  return async dispatch => {
    await HttpClient.put(
      `/web${
        [UserType.technician, UserType.provider].includes(type)
          ? '/vend/vendor'
          : '/dentist'
      }/remove_owner`,
      {id: id},
    );
    dispatch(fetchUserInfo());
  };
}

export function addIntro(value) {
  return async dispatch => {
    await HttpClient.put('/web/vend/vendor/my_info', {
      info: {
        intro: value,
      },
    });
    dispatch(fetchUserInfo());
  };
}

export function updateAlbum(fileList) {
  return async dispatch => {
    const files = fileList.filter(fl => fl.id);
    await HttpClient.put('/web/vend/vendor/my_info', {
      info: {
        album: files.map(f => f.id),
      },
    });
    dispatch(fetchUserInfo());
  };
}

export function toggleBusyDate(dateStr) {
  return async (dispatch, getState) => {
    const {
      user: {busy_dates, id},
    } = getState();
    const targetDay = busy_dates.find(date => date.date == dateStr);
    if (targetDay) {
      await HttpClient.delete(`/web/vend/busydate/${targetDay.id}`);
    } else {
      await HttpClient.post('/web/vend/vendor/busydate', [
        {vendor: id, date: dateStr},
      ]);
    }
    dispatch(fetchUserInfo());
  };
}

export function updateAddress(location) {
  return async (dispatch, getState) => {
    const {user} = getState();
    const payload = {
      latitude: location.latitude,
      longitude: location.longitude,
      address_1: location.address,
      country: location.country,
    };
    let params = null;
    if ([UserType.clinic, UserType.dentist].includes(user.type)) {
      params = {
        ...payload,
      };
    } else {
      params = {
        info: {
          ...payload,
        },
      };
    }
    try {
      const profileRep = await HttpClient.put(
        `/web/${
          [UserType.clinic, UserType.dentist].includes(user.type)
            ? UserType.dentist
            : 'vend/vendor'
        }/my_info`,
        params,
      );
      // console.log(profileRep);
      dispatch(fetchUserInfo());
    } catch (e) {
      Toast.show(e.message);
    }
  };
}

export function updateContact(payload) {
  return async (dispatch, getState) => {
    const {user} = getState();
    let params = null;
    if ([UserType.clinic, UserType.dentist].includes(user.type)) {
      params = {
        ...payload,
      };
    } else {
      params = {
        info: {
          ...payload,
        },
      };
    }
    try {
      const profileRep = await HttpClient.put(
        `/web/${
          [UserType.clinic, UserType.dentist].includes(user.type)
            ? UserType.dentist
            : 'vend/vendor'
        }/my_info`,
        params,
      );
      // console.log(profileRep);
      dispatch(fetchUserInfo());
    } catch (e) {
      Toast.show(e.message);
    }
  };
}
